package com.shunhe.storage.ui.contact;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatEditText;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.ruitu.arad.Arad;
import com.ruitu.arad.base.BaseActivity;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.router_module.Logg;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.util.ViewUtil;
import com.shunhe.storage.R;
import com.shunhe.storage.dao.model.Customer;
import com.shunhe.storage.dao.model.JsonBean;
import com.shunhe.storage.support.util.GetJsonDataUtil;

import org.json.JSONArray;

import java.util.ArrayList;

public class AddCustomerActivity extends BaseActivity {
    private AppCompatEditText et_cust_name, et_contact, et_phone, et_address;
    private TextView tv_area, tv_save;// 省市区 保存
    private RelativeLayout rl_5;

    private String custName;
    private String contact;
    private String phone;
    private String area;
    private String address;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_add_customer;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        et_cust_name = findViewById(R.id.et_cust_name);
        et_contact = findViewById(R.id.et_contact);
        et_phone = findViewById(R.id.et_phone);
        et_address = findViewById(R.id.et_address);
        tv_save = findViewById(R.id.tv_save);
        tv_area = findViewById(R.id.tv_area);
        rl_5 = findViewById(R.id.rl_5);

        setHeadTitle("客户管理");

        setListeners();

    }

    private void setListeners() {
        setOnClickListener(tv_save, rl_5);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == rl_5) {// 选择省市区
            initJsonData();
            ShowPickerView();
        }
        if (v == tv_save) {// 保存
            custName = ViewUtil.getTxt(et_cust_name);
            contact = ViewUtil.getTxt(et_contact);
            phone = ViewUtil.getTxt(et_phone);
            area = ViewUtil.getTxt(tv_area);
            address = ViewUtil.getTxt(et_address);
            if (TextUtils.isEmpty(custName)) {
                ToastUtils.showShort("请输入客户名称");
                return;
            }
            if (TextUtils.isEmpty(contact)) {
                ToastUtils.showShort("请输入联系人");
                return;
            }
            if (TextUtils.isEmpty(phone)) {
                ToastUtils.showShort("请输入电话");
                return;
            }
            if (TextUtils.isEmpty(area)) {
                ToastUtils.showShort("请选择省市区");
                return;
            }
            if (TextUtils.isEmpty(address)) {
                ToastUtils.showShort("请输入地址");
                return;
            }

            String info = custName + contact + phone + area + address;
            Logg.i("info = " + info);
            ToastUtils.showShort("info = " + info);

            Customer customer = new Customer();
            customer.setPhone(phone);
            customer.setAddress(area + address);
            customer.setName(custName);
            Arad.bus.post(new EventModel(20121751, customer));

            finish();
        }
    }

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private void initJsonData() {//解析数据
        // 注意：assets 目录下的Json文件仅供参考,实际使用可自行替换文件,关键逻辑在于循环体
        String JsonData = new GetJsonDataUtil().getJson(this, "city.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

//         * 添加省份数据
//         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
//         * PickerView会通过getPickerViewText方法获取字符串显示出来。
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getAreaList() == null || jsonBean.get(i).getCityList().get(c).getAreaList().size() == 0) {
                    City_AreaList.add("");
                } else {
                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getAreaList().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getAreaList().get(d).getName();
                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }
            //添加城市数据
            options2Items.add(CityList);
            //添加地区数据
            options3Items.add(Province_AreaList);
        }
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

    private void ShowPickerView() {// 弹出选择器
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String opt1tx = options1Items.size() > 0 ? options1Items.get(options1).getPickerViewText() : "";
                String opt2tx = options2Items.size() > 0 && options2Items.get(options1).size() > 0 ? options2Items.get(options1).get(options2) : "";
                String opt3tx = options2Items.size() > 0 && options3Items.get(options1).size() > 0 && options3Items.get(options1).get(options2).size() > 0 ? options3Items.get(options1).get(options2).get(options3) : "";

                String tx = opt1tx + opt2tx + opt3tx;
                area = tx;
                tv_area.setText(area);
            }
        })
                .setTitleText("选择区域")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }
}